﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateLambda
{
    class LambdaDemo
    {
        public void Test1()
        {
            //委托变量和方法关联(以前方法)
            CalculatorDelegate cal1 = Add;

            //委托变量可以直接关联一个"匿名方法"
            CalculatorDelegate cal2 = delegate (int a, int b)
            {
                return a + b;
            };

            //将匿名方法用Lambda表达式简化
            CalculatorDelegate cal3 = (int a, int b) => { return a + b; };

            //测试
            Console.WriteLine("通过匿名方法计算cal2:" + cal2(10,20));
            Console.WriteLine("通过Lambda表达式计算cal3:" + cal3(10, 20));


            //进一步简化Lambda表达式的方法(只适合只有一行代码的情况)
            CalculatorDelegate cal4 = (int a, int b) => a + b;
            CalculatorDelegate cal5 = (a, b) => a + b; //根据委托定义自动推断出来

            Console.WriteLine("通过Lambda表达式计算cal4:" + cal4(10, 20));
            Console.WriteLine("通过Lambda表达式计算cal5:" + cal5(10, 20));
            //Console.WriteLine("通过Lambda表达式计算cal5:" + cal5(10.7, 20.6)); //这个是错误的

            SayHelloDelegate sayHello = delegate ()
            {
                return "学习c#上位机";
            };
            SayHelloDelegate sayHello2 = () => "学习上位机";
            Console.WriteLine(sayHello());
            Console.WriteLine(sayHello2());

        }

        private int Add(int a, int b)
        {
            return a + b;
        }
    }

    //定义两个参数的委托
    public delegate int CalculatorDelegate(int a, int b);

    //定义一个无参数委托
    public delegate string SayHelloDelegate();
}
